package com.example.recyclerviewdemo.demo0.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import com.example.recyclerviewdemo.Demo0AdapterListener
import com.example.recyclerviewdemo.R

class Demo0Adapter(private val mContext: Context): RecyclerView.Adapter<Demo0Adapter.ItemViewHolder>() {

    private var items = mutableListOf<String>()      //数据源
    fun clearList(){
        items.clear()
        notifyDataSetChanged() //刷新所有列表
    }
    fun addList(list: MutableList<String>){
        items.addAll(list)
        notifyItemRangeChanged(items.size - list.size - 1,list.size)  //刷新对应下标范围的数据  第一个参数的开始刷新的位置，第二个刷新item的个数
    }
    fun setNewList(list: MutableList<String>){
        items.clear()
        items.addAll(list)
        notifyDataSetChanged()
    }

    fun getItems(): MutableList<String>{
        return items
    }

    private lateinit var demo0AdapterListener: Demo0AdapterListener
    fun setDemo0AdapterListener(mainAdapterListener: Demo0AdapterListener){
        this.demo0AdapterListener = mainAdapterListener
    }

    /**
     * ViewHolder
     * */
    inner class ItemViewHolder(view: View): RecyclerView.ViewHolder(view){
        val textView: TextView = view.findViewById(R.id.textView)
        val rootView: ConstraintLayout = view.findViewById(R.id.rootView)
    }

    /**
     * 用于onCreateViewHolder时创建不同的 ViewHolder
     * */
    override fun getItemViewType(position: Int): Int {
        return super.getItemViewType(position)
    }

    /**
     * @param parent 这里应该是RecyclerView
     * @param viewType getItemViewType(position: Int)传过来的
     * 创建 ViewHolder
     * */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val view = LayoutInflater.from(mContext).inflate(R.layout.item_demo0, parent,false)
        val itemViewHolder = ItemViewHolder(view)
        itemViewHolder.rootView.setOnClickListener {
            if(::demo0AdapterListener.isInitialized){
                demo0AdapterListener.clickItems(itemViewHolder.adapterPosition)
            }
        }
        return itemViewHolder

    }

    /**
     * 用于差异化更新
     * 使用payloads进行数据对比，再酌情进行数据的刷新
     * */
    override fun onBindViewHolder(
        holder: ItemViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        super.onBindViewHolder(holder, position, payloads)
    }

    /**
     * 对ViewHolder进行数据绑定
     * */
    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        holder.textView.text = items[position]
    }

    /**
     * 决定 RecyclerView 的子View个数
     * */
    override fun getItemCount(): Int {
        return items.size
    }

}